package com.dispacher.processor.impl;

import com.dispacher.config.GlobalConfig;
import com.dispacher.context.ResponseContext;
import com.dispacher.log.LogFactory;
import com.dispacher.log.Logger;
import com.dispacher.processor.Processor;
import com.dispacher.util.ClassUtil;
import com.dispacher.util.JsonUtil;
import com.dispacher.util.MethodUtil;

public class DefaultProcessor implements Processor {

	private static Logger log = LogFactory.getDefaultLog();

	private String url = null;

	public void setRequestURL(String url) {
		this.url = url;
	}

	public String doProcess() {
		String[] patterns = url.split("/");
		Object instance = findInstance(patterns[0]);
		String dispatcherUrl = null;
		Object returnResult = MethodUtil.invoke(patterns[1], instance, null);
		if (returnResult instanceof String) {
			log.log("with the return url : " + dispatcherUrl);
			return dispatcherUrl;
		}
		if (returnResult != null) {
			ResponseContext.responseJson(returnResult);
		}
		return null;
	}

	private Object findInstance(String url) {
		String[] urlsuffixs = GlobalConfig.getUrlSuffix();
		for (String urlsuffix : urlsuffixs) {
			Object result = ClassUtil.findInstance(urlsuffix + "." + url);
			if (result != null) {
				return result;
			}
		}
		return null;
	}

}
